<template>
  <view class="container">
    <!-- 顶部组件 -->
    <u-navbar
      id="nav-bar"
      :is-back="true"
      :background="{ background: '#fff' }"
      :border-bottom="false"
      title="购物车"
    ></u-navbar>
    <view class="content">
      <!-- 没有商品 -->
      <view class="no-goods" v-if="cartGoods.length == 0">
        <image
          class="no-goods-img"
          src="/static/images/all-noData.png"
          mode=""
        ></image>
      </view>

      <!-- 有商品 -->
      <view class="have-goods" id="have_goods" v-if="cartGoods.length !== 0">
        <!-- <view class="cart-header">
          <view class="header-edit" @click.stop="handleEdit(!isEditing)">
            <text v-if="!isEditing">编辑</text>
            <text v-else>退出编辑</text>
          </view>
        </view> -->
        <view v-for="(item, index) in cartGoods" class="shop-card" :key="index">
          <!-- <view class="shop-title u-flex">
            <image
              :src="item.checked ? checked_img : unchecked_img"
              class="checked-img"
              @click="selectGroupAll(item)"
            >
            </image>
            <image class="dpImg" src="/static/images/cart-dp.png" />
            <text class="title">{{ item.name }}</text>
          </view> -->

          <u-swipe-action
            :show="item.show"
            :options="options"
            @open="(oIndex) => openAction(item, oIndex)"
            @click="(dIndex, bIndex) => goodsClick(item, dIndex)"
          >
            <view class="goods-box">
              <view class="goods-box_in">
                <image
                  :src="item.checked ? checked_img : unchecked_img"
                  class="checked-img"
                  @click="selectGoods(item)"
                ></image>
                <view class="goods-img">
                  <image :src="item.imgUr.split('|')[0]" mode="aspectFill" />
                </view>
                <view class="detail">
                  <view class="name u-line-2">
                    {{ item.name || '' }}
                  </view>
                  <view class="info u-line-2">
                    {{ item.info || '' }}
                  </view>
                  <view class="exchangeMethod">
                    <u-input
                      v-model="item.exchangeMethod"
                      type="select"
                      :border="false"
                      @click="handleExchangeMethod(item, index)"
                    />
                  </view>
                  <!-- <view class="specLabel">{{ item.specLabel || "-" }}</view> -->
                  <view class="price-box u-flex">
                    <view class="price">
                      ¥{{ item.price || 0 }}
                      <!-- <text class="unit">¥</text>
                    <text class="text">{{ item.price.split('.')[0] }}</text>
                    <text class="decimal">
                      .{{ item.price.split('.')[1] || '00' }}
                    </text> -->
                    </view>
                    <view class="count">
                      <u-number-box
                        :input-width="42"
                        :input-height="42"
                        :size="22"
                        bg-color="#fbfbfb"
                        color="#666"
                        :min="1"
                        :max="999"
                        :value="item.count"
                        :index="index"
                        @change="changeCount(item, $event)"
                      ></u-number-box>
                    </view>
                  </view>
                </view>
              </view>
              <view v-if="item.exchangeMethod === '合伙人兑换'" class="phone">
                <view class="phone-label">伙伴手机号</view>
                <u-input
                  class="phone-input"
                  input-align="right"
                  v-model="phone"
                  placeholder="伙伴手机号"
                />
              </view>
            </view>
          </u-swipe-action>
        </view>
      </view>

      <!-- 结算 -->
      <view class="settlement" v-if="cartGoods.length != 0">
        <view class="left">
          <view class="selectAll" @click="selectAll">
            <image
              :src="allSelected ? checked_img : unchecked_img"
              class="select_img"
            ></image>
            <view>全选</view>
          </view>
          <view class="total">
            <text class="label">共：</text>
            <view class="price">{{ cartGoods.length || 0 }} 件</view>
          </view>
          <view class="total">
            <text class="label">合计：</text>
            <view class="price"
              >￥{{ (totalPrice && totalPrice.toFixed(2)) || 0 }}
            </view>
          </view>
        </view>

        <view v-if="isEditing" class="confirm" @click="handleDel()">删除</view>
        <view v-else class="confirm" @click="confirm">
          去结算
          <text v-if="totalQuantity">({{ totalQuantity }})</text>
        </view>
      </view>
    </view>

    <u-action-sheet
      :list="exchangeMethodList"
      v-model="showExchangeMethods"
      @click="exchangeMethodCallback"
    ></u-action-sheet>
  </view>
</template>
<script>
import service from '@/common/service.js';
import { showToast } from '@/common/utils';

export default {
  data() {
    return {
      cartGoods: [
        {
          id: 0,
          name: '汇来米智能机',
          imgUr: '',
          info: '真商产品智能机',
          exchangeMethod: '平台兑换',
          checked: false,
          price: 100,
          count: 1,
        },
      ],
      shopList: [],
      checked_img: '/static/images/checked.png',
      unchecked_img: '/static/images/unchecked.png',
      totalPrice: 0,
      totalQuantity: 0,
      totalBackIntegral: 0,
      allSelected: false,
      noticeList: [],
      isEditing: false,
      myInfo: {},
      options: [
        {
          text: '删除',
          style: {
            backgroundColor: '#E52E2E',
          },
        },
      ],
      exchangeMethodList: [
        {
          text: '平台兑换',
        },
        {
          text: '合伙人兑换',
        },
      ],
      showExchangeMethods: false,
      currentGoods: {},
    };
  },
  onLoad() {
    //  this.getMyInfo();
  },
  onShow() {
    // let cartData = uni.getStorageSync('cartGoods');
    // this.allSelected = false;
    // if (cartData) {
    //   this.cartGoods = cartData;
    // } else {
    //   uni.setStorageSync('cartGoods', this.cartGoods);
    // }
    // this.calculateTotalData();
  },
  methods: {
    // getMyInfo() {
    //   const that = this;
    //   const param = {};
    //   service.getMyInfo(
    //     param,
    //     function (res) {
    //       if (res && res.code == '0000') {
    //         that.myInfo = res.data;
    //       }
    //     },
    //     function (res) {}
    //   );
    // },
    handleExchangeMethod(item, index) {
      this.showExchangeMethods = true;
      this.currentGoods = {
        index: index,
        item: item,
      };
    },
    exchangeMethodCallback(index) {
      this.cartGoods[this.currentGoods.index].exchangeMethod =
        this.exchangeMethodList[index].text;
    },
    openAction(item, oIndex) {
      this.cartGoods[oIndex].show = true;
      this.cartGoods.forEach((val, idx) => {
        if (oIndex != idx) {
          this.cartGoods[oIndex].show = false;
        }
      });
    },
    selectGoods(item) {
      item.checked = !item.checked;
      this.isCheckAll();
    },
    // selectGroupAll(data) {
    //   if (data.checked) {
    //     data.goods.forEach((item) => {
    //       item.checked = false;
    //     });
    //     data.checked = false;
    //   } else {
    //     data.goods.forEach((item) => {
    //       item.checked = true;
    //     });
    //     data.checked = true;
    //   }
    //   this.isCheckAll();
    // },
    isCheckAll() {
      var isCheckAll = true;
      this.cartGoods.forEach((item) => {
        if (!item.checked) {
          isCheckAll = false;
        }
      });
      this.allSelected = isCheckAll;
      this.calculateTotalData();
    },
    selectAll() {
      if (this.allSelected) {
        this.cartGoods.forEach((item) => {
          item.checked = false;
        });
        this.allSelected = false;
      } else {
        this.cartGoods.forEach((item) => {
          item.checked = true;
        });
        this.allSelected = true;
      }
      this.calculateTotalData();
    },
    changeCount(item, e) {
      const newCount = parseInt(e.value);
      let newCartGoods = [];
      this.cartGoods.forEach((oldItem) => {
        if (item.specCode) {
          if (oldItem.specCode == item.specCode) {
            oldItem.count = newCount;
            oldItem.price = parseFloat(oldItem.singlePrice * newCount).toFixed(
              2
            );
            newCartGoods.push(oldItem);
          } else {
            newCartGoods.push(oldItem);
          }
        } else {
          if (oldItem.id == item.id) {
            oldItem.count = newCount;
            oldItem.price = parseFloat(oldItem.singlePrice * newCount).toFixed(
              2
            );
            newCartGoods.push(oldItem);
          } else {
            newCartGoods.push(oldItem);
          }
        }
      });
      this.cartGoods = newCartGoods;
      uni.setStorageSync('cartGoods', newCartGoods);
      this.calculateTotalData();
    },
    handleEdit(isEditing) {
      this.isEditing = isEditing;
    },
    goodsClick(data, index) {
      const that = this;
      uni.showModal({
        title: '提示',
        content: '确认删除当前商品',
        showCancel: true,
        cancelText: '再想想',
        confirmText: '确定',
        confirmColor: '#E52E2E',
        success: function (res) {
          if (res.cancel) {
            return;
          }
          that.cartGoods.splice(index, 1);
          uni.setStorageSync('cartGoods', that.cartGoods);
          that.calculateTotalData();
        },
      });
    },
    handleDel() {
      let chooseProducts = [];
      let delCount = 0;
      this.cartGoods.forEach((item) => {
        if (!item.checked) {
          chooseProducts.push(item);
        } else {
          delCount += 1;
        }
      });
      if (delCount === 0) {
        showToast('请选择要删除的商品');
        return;
      }
      this.cartGoods = chooseProducts;
      uni.setStorageSync('cartGoods', that.cartGoods);
      that.calculateTotalData();
    },
    calculateTotalData() {
      let totalPrice = 0;
      let totalBackIntegral = 0;
      this.cartGoods.forEach((item) => {
        if (item.checked) {
          totalPrice += parseFloat(item.price);
          if (item.buyType == 1) {
            totalBackIntegral -= parseFloat(item.backIntegral) * item.count;
          } else {
            totalBackIntegral += parseFloat(item.backIntegral) * item.count;
          }
        }
      });
      this.totalPrice = totalPrice;
      this.totalBackIntegral = totalBackIntegral;
    },
    confirm() {
      let products = [];
      let productDataList = [];
      if (this.cartGoods.length > 0) {
        this.cartGoods.forEach((item) => {
          if (item.checked) {
            let product = {
              productId: item.id,
              num: item.count,
            };
            if (
              item.specCode != '' &&
              item.specCode != 'null' &&
              item.specCode != null
            ) {
              product = {
                productId: item.id,
                num: item.count,
                skuCode: item.specCode,
              };
            }
            products.push(product);
            productDataList.push(item);
          }
        });
        if (products.length > 0) {
          uni.setStorageSync('tempProducts', products);
          uni.setStorageSync('tempProductDataList', productDataList);
          uni.navigateTo({
            url: '/pages/order/confirmOrder',
          });
        } else {
          showToast('请选择要付款的商品');
        }
      } else {
        showToast('请先去挑选喜爱的商品');
      }
    },
  },
};
</script>

<style lang="scss">
.container {
  position: relative;
  width: 100%;
  min-height: 100vh;
  padding: 0 0 120rpx;
  background-color: #f5f5f5;
}

.content {
  position: relative;
  width: 100%;
  z-index: 9;
}

.have-goods {
  font-size: 32rpx;
  padding: 15px;
  background: transparent;
  overflow: hidden;

  .shop-card {
    margin-bottom: 30rpx;
    width: 100%;
    padding: 30rpx;
    background: #ffffff;
    border-radius: 20rpx;

    .shop-title {
      margin-bottom: 20rpx;
      width: 100%;
      padding: 0 24rpx;

      .dpImg {
        margin: 0 10rpx 0 18rpx;
        width: 26rpx;
        height: 26rpx;
      }

      .title {
        font-size: 26rpx;
        color: #000000;
        font-weight: bold;
      }

      .tips {
        margin-left: auto;

        image {
          width: 23rpx;
          height: 23rpx;
        }

        text {
          font-size: 28rpx;
          color: #666;
          margin-left: 8rpx;
        }
      }
    }
  }
}

.checked-img {
  margin-top: 20rpx;
  min-width: 34rpx;
  width: 34rpx;
  height: 34rpx;
}

.goods-box {
  position: relative;
  display: flex;
  flex-direction: column;
  width: 100%;
  .goods-box_in {
    position: relative;
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    width: 100%;
  }

  .goods-img {
    width: 144rpx;
    height: 144rpx;
    margin: 0 20rpx 0 18rpx;
    border-radius: 10rpx;
    overflow: hidden;
    background-color: #eeeeee;

    image {
      width: inherit;
      height: inherit;
    }
  }

  .detail {
    flex: 1;
    max-width: 440rpx;
    color: #333;
    font-size: 26rpx;

    .label {
      padding: 0 20rpx;
      margin-right: 6rpx;
      height: 32rpx;
      font-size: 22rpx;
      border-radius: 16rpx;
      color: #999999;
      background-color: #f5f7f9;
      border: 1.5rpx solid #f5f7f9;
    }

    .name {
      height: 36rpx;
      line-height: 36rpx;
      font-weight: bold;
      font-size: 28rpx;
      color: #333333;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .info {
      margin-top: 16rpx;
      width: 100%;
      font-family: PingFang SC, sans-serif;
      font-weight: 400;
      font-size: 24rpx;
      color: #999999;
      line-height: 1;
    }

    .props-box {
      max-width: 100%;
      display: inline;
      // align-items: center;
      height: 36rpx;
      margin-top: 6rpx;
      border-radius: 8rpx;
      font-size: 22rpx;
      color: #666;
      background-color: #f5f7f9;

      .prop {
        margin: 0 12rpx;
        // margin-right:16rpx;
        // overflow: hidden;
        // text-overflow:ellipsis;
        // white-space: nowrap;
      }
    }

    .exchangeMethod {
      margin-top: 15rpx;
      width: 100%;
      padding: 0 15rpx;
      font-weight: 400;
      font-size: 24rpx;
      color: #333333;
      background: #f7f7f7;
      border-radius: 10rpx;
    }

    .specLabel {
      display: inline-block;
      margin-top: 18rpx;
      width: 100%;
      height: 42rpx;
      line-height: 42rpx;
      padding: 0 15rpx;
      font-size: 22rpx;
      font-weight: normal;
      color: #999393;
      background: #f7f7f7;
      border-radius: 10rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .price-box {
      margin-top: 20rpx;
      justify-content: space-between;

      .price {
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: flex-end;
        color: #e52e2e;
        .unit {
          margin-bottom: 4rpx;
          margin-right: 6rpx;
          font-size: 26rpx;
          line-height: 1;
        }
        .text {
          font-size: 42rpx;
          font-weight: bold;
          line-height: 1;
        }
        .decimal {
          font-size: 26rpx;
          line-height: 1;
          font-weight: bold;
        }
        // .integral {
        //   margin-left: 14rpx;
        //   font-size: 20rpx;
        //   line-height: 1;
        //   font-weight: normal;
        //   color: #E52E2E;
        // }
      }
    }
  }
}

.goods_count {
  position: absolute;
  bottom: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 120rpx;

  view {
    width: 54rpx;
    height: 40rpx;
    border-radius: 6rpx;
    line-height: 40rpx;
    text-align: center;
    background-color: #f4f4f4;
    color: #222;
  }

  image {
    width: 16rpx;
    height: 16rpx;
  }

  image:nth-child(1) {
    height: 4rpx;
  }
}

.no-goods {
  margin: 0;
  text-align: center;
  font-size: 26rpx;

  image {
    width: 494rpx;
    margin-top: 120rpx;
    margin-bottom: 120rpx;
  }

  view {
    color: #777;
    margin: 24rpx auto;
  }

  .btn {
    width: 190rpx;
    height: 60rpx;
    border: 1rpx solid #ff2a00;
    border-radius: 30rpx;
    color: #ff2a00;
    margin: 0 auto 54rpx;
    line-height: 56rpx;
  }
}

.settlement {
  position: fixed;
  display: flex;
  align-items: center;
  justify-content: space-between;
  bottom: 0;
  left: 0;
  height: auto;
  width: 100%;
  padding: 10rpx 30rpx 65rpx;
  font-size: 24rpx;
  color: #2f2f2f;
  border-top: 1rpx solid #e6e6e6;
  border-bottom: 1rpx solid #e6e6e6;
  background-color: #fff;
  z-index: 1;
  .left {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    width: calc(100% - 180rpx);
    .selectAll {
      display: flex;
      align-items: center;
      width: 100rpx;
      image {
        margin-right: 10rpx;
        width: 32rpx;
        height: 32rpx;
      }
    }
    .total {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      font-size: 24rpx;
      font-weight: bold;
      color: #333333;
      line-height: 1;
      .label {
        display: inline-block;
        width: auto;
        margin-left: 10rpx;
      }
      .price {
        font-size: 28rpx;
        color: #f03434;
        font-weight: bold;
      }
    }
  }

  .confirm {
    width: 200rpx;
    height: 74rpx;
    padding: 0 30rpx;
    line-height: 74rpx;
    font-weight: bold;
    font-size: 26rpx;
    color: #ffffff;
    text-align: center;
    background: linear-gradient(90deg, #332108, #201403);
    border-radius: 12rpx;
  }
}

.select_img {
  width: 34rpx;
  height: 34rpx;
}

// .cart-header {
//   position: relative;
//   width: 100%;
//   .header-edit {
//     position: absolute;
//     top: 40rpx;
//     right: 30rpx;
//     display: flex;
//     align-items: center;
//     width: auto;
//     height: 60rpx;
//     padding: 0 30rpx;
//     line-height: 60rpx;
//     font-size: 28rpx;
//     font-weight: normal;
//     color: #E52E2E;
//     text-align: center;
//     border: 2rpx solid #E52E2E;
//     border-radius: 30rpx;
//   }
// }

.phone {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  margin-top: 25rpx;
  width: 100%;
  height: 106rpx;
  padding: 30rpx;
  background: #f7f7f7;
  border-radius: 20rpx;
  text-align: right;
  .phone-label {
    font-family: PingFang SC, sans-serif;
    font-weight: bold;
    font-size: 28rpx;
    color: #333333;
    text-align: left;
  }

  .phone-input {
    flex: 1;
    min-width: 0;
  }
}
</style>
